'use strict';

const fs = require('fs');
const path = require('path');
const { Service } = require('egg');
const pump = require('mz-modules/pump');

class CommonService extends Service {
  /**
   * 公共上传
   * @return 文件地址
   */
  async upload() {
    const { ctx, config } = this;
    const uploadBasePath = 'app/public/upload';
    // 获取文件流
    const stream = await ctx.getFileStream();
    // 创建文件夹
    const folderName = ctx.helper.dateFormat(Date.now());
    const dirName = path.join(config.baseDir, uploadBasePath, folderName);
    if (!fs.existsSync(dirName)) fs.mkdirSync(dirName);
    // 生成文件名
    const extName = path.extname(stream.filename); // 扩展名
    const name = stream.filename.split(extName)[0]; // 原始文件名
    const filename =
      name + '_' + ctx.helper.dateFormat(Date.now(), 'YYYYMMDDhhmmss') + extName.toLowerCase();
    // 生成保存路径
    const target = path.join(dirName, filename);
    // 创建写入文件流
    const writeStream = fs.createWriteStream(target);
    try {
      // 写入文件
      await pump(stream, writeStream);
    } catch (error) {
      throw error;
    }
    const url = `http://${ctx.host}/public/upload/${folderName}/${filename}`;

    return url;
  }
}

module.exports = CommonService;
